// components/GlobalLoading.tsx
import React, { useState, useEffect } from "react";
import { View, Modal, ActivityIndicator, StyleSheet } from "react-native";
import { useTheme } from "@/contexts/ThemeContext";

// 接口定义为全局，但不在此处声明命名空间，避免重复声明
interface LoadingProps {
  visible?: boolean;
}

const Loading = ({ visible: propVisible }: LoadingProps) => {
  const { colors } = useTheme();
  // 如果传入了visible属性，则使用它，否则默认为false
  const [internalVisible, setInternalVisible] = useState(false);

  // 支持通过props控制可见性
  useEffect(() => {
    if (propVisible !== undefined) {
      setInternalVisible(propVisible);
    }
  }, [propVisible]);

  // 结合两种使用方式
  const visible = propVisible !== undefined ? propVisible : internalVisible;

  const show = () => setInternalVisible(true);
  const hide = () => setInternalVisible(false);

  // 暴露方法给外部使用
  if (typeof window !== "undefined") {
    // 确保全局命名空间存在
    (window as any).GlobalLoadingNamespace = {
      show,
      hide,
    };
  }

  return (
    <Modal
      transparent
      visible={visible}
      animationType="fade"
      onRequestClose={hide}
    >
      <View style={styles.container}>
        <View
          style={[
            styles.loadingBox,
            {
              backgroundColor: colors.background,
              shadowColor: colors.card.shadow,
            },
          ]}
        >
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.2)",
  },
  loadingBox: {
    padding: 30,
    borderRadius: 10,
    elevation: 5,
  },
});

export default Loading;
